﻿using QD.LopPlat.UI.Code.DbContent;
using QD.LopPlat.UI.Model.Sys;
using QD.SQLHelper;
using System.Linq;
using System.Windows.Forms;

namespace QD.LopPlat.UI.Code
{
    public static class QDDataBaseHelper
    {
        /// <summary>
        /// 当前登录应用
        /// </summary>
        public static QDDataBase CurQDDataBase;

        /// <summary>
        /// 取登录应用
        /// </summary>
        public static QDDataBase GetQDDataBase(string qfCode)
        {
            DbQfDevPlat db = new DbQfDevPlat();
            QDDataBase dbBase = db.QDDataBase.First(p => p.QfCode == qfCode);
            return dbBase;
        }

        /// <summary>
        /// 取指定应用的数据库连接字符串
        /// </summary>
        /// <param name="qfCode"></param>
        /// <returns></returns>
        public static string GetDbConnectionString(string qfCode)
        {
            DbQfDevPlat PlatConfig = new DbQfDevPlat();
            QDDataBase dbMod = PlatConfig.QDDataBase.Single(p => p.QfCode == qfCode);

            LogonConfig logonConfig = (LogonConfig)DbConfig.Instance.LogonConfig.Clone();
            string dbConnectionString = logonConfig.GetConnectionStrings(dbMod.ConfigDataBase);

            return dbConnectionString;
        }

        /// <summary>
        /// 登录应用
        /// </summary>
        /// <param name="isApplicationExit">退出时是否退出整个程序</param>
        /// <returns></returns>
        public static bool LoginQataBase(string qfCode, string qfName, bool isApplicationExit)
        {
            DbQfDevPlat dbPlat = new DbQfDevPlat();

            //因为应用可能是从其它客户端传过来的，所以必须再次判断
            QDDataBase mod = dbPlat.QDDataBase.FirstOrDefault(p => p.QfCode == qfCode && p.QfName == qfName);
            if (mod == null)
            {
                Tools.PromptHelper.Prompt("应用 [" + qfCode + "：" + qfName + "] 不存在!");
                return false;
            }

            QDDataBaseHelper.CurQDDataBase = mod;

            DbConfig.Instance.QfCode = qfCode;
            DbConfig.Instance.QfName = qfName;

            DbConfig.Instance.DbMasterName = mod.MasterDataBase;
            DbConfig.Instance.DbConfigName = mod.ConfigDataBase;

            //Form pcFrm = Application.OpenForms["QDDevPlat"];
            //if (pcFrm != null)
            //{
            //    QDDevPlat frm = (QDDevPlat)pcFrm;
            //    frm.ApplicationExit = false;
            //    frm.Close();
            //}

            //QDDevPlat pt = new QDDevPlat();
            //pt.Show();
            //pt.Activate();
            //pt.ApplicationExit = isApplicationExit;

            return true;
        }
    }
}
